import { ipcMain } from 'electron'
import * as projectService from '../services/projectService'
import { Project as EntityProject } from '../database/entities/Project'
import { Project as DbProject } from '../database/index'

/**
 * 将数据库项目转换为实体项目
 */
function convertToEntityProject(dbProject: DbProject): Partial<EntityProject> {
  return {
    id: dbProject.id?.toString(),
    name: dbProject.name,
    description: dbProject.description,
    createdAt: dbProject.createdAt,
    updatedAt: dbProject.updatedAt
  }
}

/**
 * 设置项目相关的IPC处理程序
 */
export function setupProjectIPC() {
  // 获取所有项目
  ipcMain.handle('project:getAll', async () => {
    try {
      const projects = await projectService.getAllProjects()
      return projects.map(convertToEntityProject)
    } catch (error) {
      console.error('获取项目列表失败:', error)
      throw new Error('获取项目列表失败')
    }
  })

  // 获取单个项目
  ipcMain.handle('project:getById', async (_event, id: string) => {
    try {
      const numId = parseInt(id, 10)
      const project = await projectService.getProjectById(numId)
      return project ? convertToEntityProject(project) : null
    } catch (error) {
      console.error(`获取项目 ${id} 失败:`, error)
      throw new Error('获取项目详情失败')
    }
  })

  // 创建新项目
  ipcMain.handle('project:create', async (_event, projectData: Partial<EntityProject>) => {
    try {
      // 确保至少有name参数
      if (!projectData.name) {
        throw new Error('项目名称不能为空')
      }
      
      // 只传递name和description参数
      const project = await projectService.createProject(projectData.name, projectData.description)
      
      // 转换为实体项目格式
      return convertToEntityProject(project)
    } catch (error) {
      console.error('创建项目失败:', error)
      throw new Error('创建项目失败')
    }
  })

  // 更新项目
  ipcMain.handle('project:update', async (_event, id: string, projectData: Partial<EntityProject>) => {
    try {
      const numId = parseInt(id, 10)
      const success = await projectService.updateProject(numId, {
        name: projectData.name,
        description: projectData.description
      })
      
      if (success) {
        const updatedProject = await projectService.getProjectById(numId)
        return updatedProject ? convertToEntityProject(updatedProject) : null
      }
      return null
    } catch (error) {
      console.error(`更新项目 ${id} 失败:`, error)
      throw new Error('更新项目失败')
    }
  })

  // 删除项目
  ipcMain.handle('project:delete', async (_event, id: string) => {
    try {
      const numId = parseInt(id, 10)
      const result = await projectService.deleteProject(numId)
      return result
    } catch (error) {
      console.error(`删除项目 ${id} 失败:`, error)
      throw new Error('删除项目失败')
    }
  })

  // 更新项目最后打开时间
  ipcMain.handle('project:updateLastOpened', async (_event, id: string) => {
    try {
      // 这个方法已被弃用，但为了保持兼容性，我们保留它
      await projectService.updateProjectLastOpened(id)
      return true
    } catch (error) {
      console.error(`更新项目 ${id} 最后打开时间失败:`, error)
      throw new Error('更新项目最后打开时间失败')
    }
  })

  // 获取最近打开的项目
  ipcMain.handle('project:getRecent', async (_event, limit: number) => {
    try {
      const projects = await projectService.getRecentProjects(limit)
      return projects.map(convertToEntityProject)
    } catch (error) {
      console.error('获取最近项目失败:', error)
      throw new Error('获取最近项目失败')
    }
  })
} 